import axios, {AxiosInstance} from "axios";
import {Toast} from "vant";
import { useRouter} from "vue-router";
const router = useRouter();
export const URL: string = import.meta.env.MODE === 'development'
    ? "http://localhost:8081/api"  // 开发环境地址
    : import.meta.env.VITE_API_URL;  // 生产环境地址，从.env.production获取

let myAxios = axios.create({
    baseURL: URL
});

myAxios.defaults.withCredentials = true; // 配置为 true
// Add a request interceptor
myAxios.interceptors.request.use(function (config) {
    console.log('我要发请求啦', config)
    // Do something before request is sent
    return config;
}, function (error) {
    // Do something with request error
    return Promise.reject(error);
});

// Add a response interceptor
myAxios.interceptors.response.use(function (response) {
    console.log('我收到后端的响应啦', response.data)
    // 未登录则跳转到登录页
    if (response?.data?.code === 40100) {
        Toast("请先登录！")
        const redirectUrl = window.location.href
        window.location.href = `/user/login?redirect=${redirectUrl}`
    }
    // Do something with response data
    return response.data;
}, function (error) {
    // Do something with response error
    return Promise.reject(error);
});

export default myAxios;
